package com.bst.bsj.portal.util;

import javax.servlet.http.HttpServletRequest;

import com.homewaimai.common.lang.StringUtil;
import com.homewaimai.framework.web.Constants;
import com.homewaimai.framework.web.request.session.AuthSecureContextHolder;
import com.homewaimai.framework.web.request.session.LoginUser;
import com.homewaimai.framework.web.request.session.UserAuthenticationContext;

public class AuthUtil {

	public static String getAuthUser() {
		UserAuthenticationContext user = AuthSecureContextHolder.getContext();
		return user.getMemberId();
	}

	public static boolean setAuthToken(HttpServletRequest request,
			LoginUser user) {
		
		String loginUser = convertLoginUserToCookie(user);
		request.getSession().setAttribute(Constants.COOKIE_LOGIN_USER,loginUser);
		return true;
	}

	private static String convertLoginUserToCookie(LoginUser user) {
		StringBuffer buffer = new StringBuffer();
		if (null != user) {
			buffer.append(LoginUser.COOKIE_LOGIN_ID).append("=").append(
					StringUtil.defaultIfBlank(
							String.valueOf(user.getLoginId()), ""));
			buffer.append('&');
			buffer.append(LoginUser.COOKIE_TS).append("=").append(
					StringUtil.defaultIfBlank(user.getTs(), ""));
			buffer.append('&');
			buffer.append(LoginUser.COOKIE_LOGINED).append("=").append(
					StringUtil.defaultIfBlank(String.valueOf(user.isLogined()),
							"false"));
			buffer.append('&');
			buffer.append(LoginUser.COOKIE_M_ID).append("=").append(
					StringUtil.defaultIfBlank(user.getMemberId(), ""));
			buffer.append('&');
			buffer.append(LoginUser.COOKIE_PWD).append("=").append(
					StringUtil.defaultIfBlank(user.getPwd(), ""));
			buffer.append('&');
			buffer.append(LoginUser.COOKIE_M_LEVEL).append("=").append(
					StringUtil.defaultIfBlank(user.getmLevel(), ""));
			buffer.append('&');
			buffer.append(LoginUser.COOKIE_NICK_NAME).append("=").append(
					StringUtil.defaultIfBlank(user.getNickName(), ""));
		}
		return buffer.toString();
	}
}
